package top.withu.gaof.freehope.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.springframework.util.StringUtils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import top.withu.gaof.freehope.model.User;

/**
 * @author Gaofan
 * @date 2019年4月24日 下午2:29:57
 * @describe jwt工具类
 */
public class JWTUtil {

	/**
	 * 生成token
	 * 
	 * @param user
	 * @return
	 */
	public static String getToken(User user) {
		Date expireDate = getAfterDate(new Date(), user.getEffectiveTime());
		String token = "";
		if (null != expireDate) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:DDD");
			user.setEffectiveTime(sdf.format(expireDate));
			token = JWT.create().withAudience(user.getUserName()).withExpiresAt(expireDate)
					.sign(Algorithm.HMAC256(user.getPwd()));
		}
		token = JWT.create().withAudience(user.getUserName()).sign(Algorithm.HMAC256(user.getPwd()));
		return token;
	}

	/**
	 * 设置token过期时间
	 * 
	 * @param date
	 *            当前时间
	 * @param year
	 *            有效年
	 * @param month
	 *            有效月数
	 * @param day
	 *            有效天数
	 * @param hour
	 *            有效小时数
	 * @param minute
	 *            有效分钟数
	 * @param second
	 *            有效秒数
	 * @return
	 */
	public static Date getAfterDate(Date date, String effectiveTime) {
		if (null == effectiveTime) {
			return null;
		}
		String[] times = effectiveTime.split("-");
		if (date == null) {
			date = new Date();
		}
		Calendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.add(Calendar.YEAR, getIntTime(times[0]));
		cal.add(Calendar.MONTH, getIntTime(times[1]));
		cal.add(Calendar.DATE, getIntTime(times[2]));
		cal.add(Calendar.HOUR_OF_DAY, getIntTime(times[3]));
		cal.add(Calendar.MINUTE, getIntTime(times[4]));
		cal.add(Calendar.SECOND, getIntTime(times[5]));
		return cal.getTime();

	}

	/**
	 * 将获取到的有效时间effectiveTime转换为int
	 * 
	 * @param str
	 * @return
	 */
	public static int getIntTime(String str) {
		if (!StringUtils.isEmpty(str) && !"0".equals(str)) {
			return Integer.valueOf(str);
		}
		return 0;
	}

	public static void main(String[] args) {
		User user = new User();
		user.setPwd("123456");
		// System.out.println(getToken(user).equals(
		// "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJBUFAifQ.3JgvjlEh6IieMbdbxZjICFScOhuggpwviYK6XpFqWLg"));
	}

}
